/*
 * ReportProblemAction.java
 *
 * Created on July 8, 2003, 11:33 AM
 */

package com.scalar.chiptrack.users.actions;

/**
 *
 * @author  Balaram Putta
 * @version
 */

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.forms.ReportProblemForm;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;


public class ReportProblemAction extends ChipTrackAction
{
    private static String SYSTEM_ADMINISTRATOR = "System Administrator";
    private static String SOURCE_PAGE = "/reportProblem.do";  // this class

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
        throws Exception
    {
        HashMap info = new HashMap();
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );

        HashMap errors = new HashMap();
        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );

        ReportProblemForm reportProblemForm = ( ReportProblemForm ) form;

        String action = request.getParameter( "action" );

        User user = null;
        HttpSession session = request.getSession();
        if( ( session == null ) || ( ( user = (User) session.getAttribute( SessionKeys.USER_KEY ) ) == null ) )
        {
            ActionForward actionForward = new ActionForward( ConfigManager.getDefaultLoginPage() + "?sourcePage=" + SOURCE_PAGE );
            return actionForward;
        }

        // Send mail
        if( "sendMail".equalsIgnoreCase( action ) )
        {
            String to = reportProblemForm.getTo();
            String from = reportProblemForm.getFrom();
            String subject = reportProblemForm.getSubject();
            String message = reportProblemForm.getMessage();

            if( message == null )
            {
                message = "";
            }
            message = message.replaceAll( "\n", "<br>" );   // for html view

            try
            {
                Mailer.send( from, to, subject, message );
                info.put( "Problem has been emailed to <b>" + to + "</b>.", null );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Internal Server Error", "Could not email the problem to System Administrator" );
            }

            request.setAttribute( "reportProblemForm", reportProblemForm );
            return( mapping.findForward( "success" ) );
        }


        // Send Mail From more_error_info.jsp Page
        // Balaram on Oct 22, 2003
        if( "sendMailFromErrorPage".equalsIgnoreCase( action ) )
        {
            String to = reportProblemForm.getTo();
            String from = reportProblemForm.getFrom();
            String subject = reportProblemForm.getSubject();
            String message = reportProblemForm.getMessage();

            if( message == null )
            {
                message = "";
            }
            message = message.replaceAll( "\n", "<br>" );   // for html view

            try
            {
                Mailer.send( from, to, subject, message );
                info.put( "Problem has been emailed to <b>" + to + "</b>.", null );
                //System.out.println( "\nTo: " + to + "\nFrom: " + from + "\nSubject: " + subject + "\nMessage: " + message + "\n\n" );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Internal Server Error", "Could not email the problem to System Administrator" );
            }

            request.setAttribute( "reportProblemForm", reportProblemForm );
            return( mapping.findForward( "errorInfoPage" ) );
        }


        // View Action
        // Balaram, Oct 22, 2003
        if( ( action == null ) || ( "shwoErrorInfoPage".equalsIgnoreCase( action ) ) )
        {
            reportProblemForm = new ReportProblemForm();

            String subject = "";
            Throwable errorReport = null;

            if( action == null )
            {
                subject = (String) session.getAttribute( SessionKeys.ERROR_REPORT_SUBJECT );
                session.removeAttribute( SessionKeys.ERROR_REPORT_SUBJECT );

                errorReport = ( Throwable ) session.getAttribute( SessionKeys.ERROR_REPORT );
                session.removeAttribute( SessionKeys.ERROR_REPORT );
            }

            if( "shwoErrorInfoPage".equalsIgnoreCase( action ) )
            {
                ErrorReport errorReportObject = ( ErrorReport ) session.getAttribute( SessionKeys.ERROR_REPORT_OBJECT );
                subject = errorReportObject.getProblem();
                errorReport = errorReportObject.getException();
            }

            StringBuffer errMessage = new StringBuffer();
            if( errorReport != null )
            {
                errMessage.append( "\n--- System Method Execution Stack Trace ---\n" );
                errMessage.append( errorReport.toString() ).append( "\n" );

                StackTraceElement[] stElement = errorReport.getStackTrace();
                for( int i=0; i<stElement.length; i++ )
                {
                    errMessage.append( stElement[i].toString() ).append( "\n" );
                }
            }

            reportProblemForm.setTo( ConfigManager.getSysAdminEmail() );
            reportProblemForm.setToName( SYSTEM_ADMINISTRATOR );
            reportProblemForm.setFrom( user.getEmail() );
            reportProblemForm.setFromName( user.getUserName() );
            reportProblemForm.setSubject( subject );
            reportProblemForm.setMessage( errMessage.toString() );

            request.setAttribute( "reportProblemForm", reportProblemForm );

            if( "shwoErrorInfoPage".equalsIgnoreCase( action ) )
            {
                return( mapping.findForward( "errorInfoPage" ) );
            }

            return( mapping.findForward( "success" ) );
        }

        return( mapping.findForward( "success" ) );
    }

}